package org.su.webadapter.render;


import org.su.generalmvc.IModel;
import org.su.generalmvc.render.IRender;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;


/**
 * 将action中的数据渲染为json格式数据，传递给浏览器
 * @author yangchuan
 *
 */
public class JspRender implements IRender {
	protected static final Log logger = LogFactory.getLog(JspRender.class);

	@Override
	public void render(IModel model, Object result, String defaultPath, ServletRequest request,
			ServletResponse response) {
		try {
			String path = (String)result;
			if(model != null && !model.isEmpty()){
				@SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) model.getModel();
				Set<Map.Entry<String, Object>> set = data.entrySet();
				for(Map.Entry<String, Object> item : set){
					request.setAttribute(item.getKey(), item.getValue());
				}
			}
			
			if (StringUtils.isNotBlank(path)) {
				if (path.startsWith("f:")) {
					request.getRequestDispatcher(path.substring(2)).forward(
							request, response);
					return;
				}

				if (path.startsWith("r:")) {
					String str = path.substring(2);
					if(str.startsWith("http")){
                        ((HttpServletResponse)response).sendRedirect(str);
					}else{
						String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+((HttpServletRequest)request).getContextPath()+"/";
                        ((HttpServletResponse)response).sendRedirect(basePath + str);
					}
					
					return;
				}
			} else {
				path = defaultPath;
			}
			
			if (!path.startsWith("pages/")) {
				if (path.startsWith("/")) {
					path = "pages" + path;
				} else {
					path = "pages/" + path;
				}
			}
		
			request.getRequestDispatcher("/WEB-INF/"+path).forward(
					request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	

}
